package com.etasist;

/**
 * @author issa
 *
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientInputOutput implements Runnable {
	private Socket incoming;
	private PrintWriter out;
	private BufferedReader in;
	
	public ClientInputOutput(Socket soket) {
		incoming = soket;
	}

	public void run() {
		try {
			
			out = new PrintWriter(incoming.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
			String inputLine;

			//while (true) {
				while ((inputLine = in.readLine()) != null) {
					/*
					 * if command = bye means exit the connection
					 */
					if (inputLine.equalsIgnoreCase("Bye")){
						out.println("QUITING AGENT ...");
						break;
					}
						
					
					/*
					 * if the allCommand = deny that means client can't run any command
					 * he can run spacifc command allowed
					 */					
					
					if(ConfigInfo.allCommands.equalsIgnoreCase("deny")){
						/*
						 * check if the provided command is granted or not
						 * granted commands are listed in ConfigInfo.allowedCommands
						 */
						if (ConfigInfo.allowedCommands.contains(inputLine)) {
							out.println("Waiting ...");
							out.println(RunCommand.runRemoreCommand(inputLine));
						} else {
							System.out.println("<"+inputLine+ "> is not authrized command!");
							out.println(inputLine+ " is not authorized command!");
						}
					} 
					
					/*
					 * if the allCommand = allow that means client can run all
					 * the command by using the agent
					 */
					
					else if(ConfigInfo.allCommands.equalsIgnoreCase("allow")){
							out.println("Waiting ...");
							out.println(RunCommand.runRemoreCommand(inputLine));
					}  
					else {
							out.println("problem in server configuration, please contact system admin");
					}
					
				}
				out.close();
				in.close();
				incoming.close();
				//Thread.sleep(100);
			//}
		} catch (IOException e) {
			out.close();
			in = null;
			incoming=null;
			e.printStackTrace();
		} 

	}

}
